//
//  TwitFormWindowController.m
//  TwitterPlane
//
//  Created by kazuyuki takahashi on 10/01/23.
//  Copyright 2010 by invisibledesigner.com. All rights reserved.
//

#import "TwitFormWindowController.h"
#import "TwitterEngineManager.h"
#import "Status.h"


static TwitFormWindowController *sInstance = nil;


@implementation TwitFormWindowController

@synthesize busy = busy_;

+ (id)sharedController
{
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        sInstance = [[self alloc] initWithWindowNibName:@"TwitFormWindow"];
    });
    return sInstance;
}

- (void)showWindow:(id)sender
{
    [self showWindow:sender replyToStatus:nil];
}


- (void)showWindow:(id)sender replyToStatus:(Status*)status
{
    if (![self isWindowLoaded]) {
        [self loadWindow];
    }
    
    [replyToStatus_ autorelease];
    replyToStatus_ = [status retain];
    
    NSString *str = @"";
    if (replyToStatus_) {
        str = [NSString stringWithFormat:@"@%@ ", [[status user] screenName]];
    }
    [textField_ setStringValue:str];

    //ウィンドウを開くときテキストフィールドにフォーカスが入っているようにする
    [[[self window] initialFirstResponder] becomeFirstResponder];
    
    //カーソルを一番後ろに
	NSText *text = [[textField_ window] fieldEditor:NO forObject:textField_];
	[text setSelectedRange:NSMakeRange([[text string] length], 0)];
    
    [super showWindow:sender];
}


- (IBAction)twit:(id)sender
{
    NSString *text = [textField_ stringValue];
    if ([text length] == 0) {
        [[NSSound soundNamed:@"Funk"] play];
        return;
    }
    
    [self setBusy:YES];
    
    NSAssert(self == sInstance, @"");
    
    TwitterEngineCallback callback = ^(BOOL succeeded, NSError *error) {
        // memo: なぜかselfを使用するとEXC_BAD_ACCESSなのでsInstanceを使う
        [sInstance setBusy:NO];
        
        if (succeeded) {
            [sInstance close];
        } else {
            [[NSSound soundNamed:@"Funk"] play];
        }
    };
    
    if (replyToStatus_) {
        [[TwitterEngineManager defaultManager] twit:text replyToStatus:replyToStatus_ callback:callback];
    } else {
        [[TwitterEngineManager defaultManager] twit:text callback:callback];
    }
}

@end
